<?php

class MPromise extends MY_Model {

    protected $table = 'user_promise';

    public static function getPromiseState($state=NULL){
        $define = array(
            '0'=>'<label class="label label-default">未缴纳</label>',
            '1'=>'<label class="label label-warning">已缴纳</label>',
            '2'=>'<label class="label label-danger">申请退还中</label>',
            '3'=>'<label class="label label-success">已退还</label>'
        );
        if($state === NULL){
            return $define;
        }else{
            return key_exists($state, $define)?$define[$state]:'';
        }
    }


    public function getList($limit){
        $this->db->select( 'p.*,u.avatar,u.nick_name');
        $this->db->distinct();
        $this->db->from($this->table.' p');
        $this->db->join('user u','p.user_id = u.id');
        $this->db->limit($limit['limit'],$limit['offset']);
        $this->formfilter->doFilter();
        $this->db->order_by('id', 'desc');
        $query = $this->db->get();
        return $query->result();
    }

    public function getCount(){
        $this->db->select('count(distinct p.id) as num');
        $this->db->from($this->table.' p');
        $this->db->join('user u','p.user_id = u.id');
        $this->formfilter->doFilter();
        $tmp = $this->db->get()->result();
        return (int)$tmp[0]->num;
    }

    public function getById($id)
    {
        $query = $this->db->where('id', $id)->get($this->table);
        return $query->row();
    }

    public function getAmount(){
        $this->db->select('sum(amount) as total_amount');
        $this->db->from($this->table);
        $this->db->where('status',1);
        $tmp = $this->db->get()->row();
        return $tmp->total_amount;
    }
    public function getLatest(){
        $this->db->select("up.*,u.nick_name,u.avatar");
        $this->db->from($this->table.' up');
        $this->db->join('user u','up.user_id = u.id','INNER');
        $this->db->where('up.status',1);
        $this->db->order_by('up.id','desc');
        $this->db->limit(20);
        return $this->db->get()->result();
    }

}
